package com.freestyle.redis.expire;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;

/**
 * Created by rocklee on 2022/2/5 10:26
 */
@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
  private List<Consumer<Message>> processes=new LinkedList<>();
  public void addProcess(Consumer<Message> process){
    processes.add(process);
  }



  /**
   * Creates new {@link MessageListener} for {@code __keyevent@*__:expired} messages.
   *
   * @param listenerContainer must not be {@literal null}.
   */
  public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
    super(listenerContainer);
  }
  @Override
  public void onMessage(Message message, byte[] pattern) {
    // 业务处理 , 注意message.toString()可以获取失效的key
    String expiredKey = message.toString();
    log.info(expiredKey + " 过期了");
    processes.forEach(c->{
      c.accept(message);
    });
  }
}
